package cn.com.ry.framework.linklog.web.interceptor;

import cn.com.ry.framework.linklog.constant.LinkLogConstants;
import cn.com.ry.framework.linklog.context.LinkLogContext;
import cn.com.ry.framework.linklog.web.common.LinkLogWebCommon;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * web controller的拦截器
 */
public class LinkLogSpringMvcInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            return preHandleByHandlerMethod(request, response, handler);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod) {
            postHandleByHandlerMethod(request, response, handler, modelAndView);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (handler instanceof HandlerMethod) {
            afterCompletionByHandlerMethod(request, response, handler, ex);
        }
    }


    public boolean preHandleByHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LinkLogWebCommon.loadInstance().preHandle(request, response, handler);
        //把traceId放入response的header，为了方便有些人有这样的需求，从前端拿整条链路的traceId
        response.addHeader(LinkLogConstants.LINKLOG_TRACE_KEY, LinkLogContext.getTraceId());
        try {
            String expose = response.getHeader("Access-Control-Expose-Headers");
            if (expose != null && !expose.equals("")) {
                expose += "," + LinkLogConstants.LINKLOG_TRACE_KEY;
                response.addHeader("Access-Control-Expose-Headers", expose);
            } else {
                response.addHeader("Access-Control-Expose-Headers", LinkLogConstants.LINKLOG_TRACE_KEY);
            }

        } catch (Exception e) {

        }
        return true;
    }

    public void postHandleByHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletionByHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LinkLogWebCommon.loadInstance().afterCompletion(request, response, handler);
    }

}
